package com.zscat.mallplus.controller;


import com.alibaba.excel.event.Order;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qimen.api.QimenClient;
import com.zscat.mallplus.annotation.IgnoreAuth;
import com.zscat.mallplus.annotation.SysLog;
import com.zscat.mallplus.dms.entity.DmsOrder;
import com.zscat.mallplus.dms.service.*;
import com.zscat.mallplus.enums.OrderStatus;
import com.zscat.mallplus.qsg.*;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.DateUtil;
import com.zscat.mallplus.utils.UserUtils;
import com.zscat.mallplus.vo.OrderVo;
import com.zscat.mallplus.vo.ReportDetailVo;
import com.zscat.mallplus.vo.ReportVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * 设备管理Controller
 */
@RestController
@Api(tags = "ReportController", description = "报表管理")
@RequestMapping("/api/dms/report")
public class ReportController {

    @Autowired
    private IReportService reportService;
    @Autowired
    private IDmsOrderService orderService;
    @Autowired
    private IQsgRechargeOrderService rechargeOrderService;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IQsgHexiaoService hexiaoService;

    @IgnoreAuth
    @GetMapping(value = "/list")
    @ApiOperation(value = "根据店铺id查询设备列表")
    public Object getAllDevice(@RequestParam(required = false) Long storeId,
                               @RequestParam(required = false) String startTime,
                               @RequestParam(required = false) String endTime) {
        try {
            QueryWrapper qw = new QueryWrapper();
            qw.ge("time", startTime);
            qw.le("time", endTime);
            if (null != storeId) {
                qw.eq("store_id", storeId);
            }
            qw.orderByDesc("time");
            return new CommonResult().success(reportService.list(qw));
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed();
        }
    }

    @IgnoreAuth
    @SysLog(MODULE = "dms", REMARK = "")
    @ApiOperation(value = "")
    @GetMapping(value = "/reportdetailgroupbypaytype")
    public Object reportdetailgroupbypaytype(@RequestParam String status, @RequestParam Long storeId, @RequestParam String payType,
                                             @RequestParam(value = "pageSize", required = false, defaultValue = "30") Integer pageSize,
                                             @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum) {
        Map<String, String> timeArea = DateUtil.getTimeArea(Integer.valueOf(status));
        String startTime = timeArea.get("startTime");
        String endTime = timeArea.get("endTime");
        ReportVo orderData = getOrderDetail(startTime, endTime, storeId);//现金订单总额以及订单数对象
        ReportVo rechargeData = getRechargeOrderDetail(startTime, endTime, storeId);//充值订单总额以及订单数对象
        ReportVo douyinData = getHexiaoDetail(startTime, endTime, storeId, 0);
        ReportVo meituanData = getHexiaoDetail(startTime, endTime, storeId, 1);
        QueryWrapper qw = new QueryWrapper();
        qw.eq("store_id", storeId);
        List<ReportDetailVo> vos = new ArrayList<>();
        if (payType.equalsIgnoreCase("0")) {
            List<Integer> statusQw = new ArrayList<>();
            statusQw.add(OrderStatus.HAS_PAYMONEY.getValue());
            statusQw.add(OrderStatus.COMPLETED.getValue());
            qw.in("order_status", statusQw);
            qw.eq("integral", 0);
            qw.orderByDesc("create_datetime");
            if (StringUtils.isNotBlank(startTime)) {
                qw.le("create_datetime", endTime);
                qw.ge("create_datetime", startTime);
            }
            IPage<DmsOrder> orderIPage = orderService.page(new Page<>(pageNum, pageSize), qw);
            vos = toReportDetail(orderIPage.getRecords(), null, null, null);
        }
        if (payType.equalsIgnoreCase("1")) {
            qw.orderByDesc("create_datetime");
            qw.eq("order_status", 2);
            if (StringUtils.isNotBlank(startTime)) {
                qw.le("create_datetime", endTime);
                qw.ge("create_datetime", startTime);
            }
            IPage<QsgRechargeOrder> rechargeOrderIPage = rechargeOrderService.page(new Page<>(pageNum, pageSize), qw);
            vos = toReportDetail(null, rechargeOrderIPage.getRecords(), null, null);
        }
        if (payType.equalsIgnoreCase("2")) {
            qw.orderByDesc("create_datetime");
            qw.eq("hexiao_type", 0);
            if (StringUtils.isNotBlank(startTime)) {
                qw.le("create_datetime", endTime);
                qw.ge("create_datetime", startTime);
            }
            IPage<QsgHexiao> douyinIPage = hexiaoService.page(new Page<>(pageNum, pageSize), qw);
            vos = toReportDetail(null, null, douyinIPage.getRecords(), null);
        }
        if (payType.equalsIgnoreCase("3")) {
            qw.orderByDesc("create_datetime");
            qw.eq("hexiao_type", 1);
            if (StringUtils.isNotBlank(startTime)) {
                qw.le("create_datetime", endTime);
                qw.ge("create_datetime", startTime);
            }
            IPage<QsgHexiao> meituanIPage = hexiaoService.page(new Page<>(pageNum, pageSize), qw);
            vos = toReportDetail(null, null, null, meituanIPage.getRecords());
        }
        Map<String, Object> result = new HashMap<>();
        int totalNum = orderData.getNum()+rechargeData.getNum()+douyinData.getNum()+meituanData.getNum();
        BigDecimal totalMoney = orderData.getMoney().add(rechargeData.getMoney()).add(douyinData.getMoney()).add(meituanData.getMoney());
        result.put("details", vos);
        result.put("totalNum",totalNum);
        result.put("totalMoney",totalMoney);
        result.put("orderDataNum",orderData.getNum());
        result.put("orderDataMoney",orderData.getMoney());
        result.put("rechargeDataNum",rechargeData.getNum());
        result.put("rechargeDataMoney",rechargeData.getMoney());
        result.put("douyinDataNum",douyinData.getNum());
        result.put("douyinDataMoney",douyinData.getMoney());
        result.put("meituanDataNum",meituanData.getNum());
        result.put("meituanDataMoney",meituanData.getMoney());
        return new CommonResult().success(result);
    }
	
	@IgnoreAuth
    @SysLog(MODULE = "dms", REMARK = "")
    @ApiOperation(value = "")
    @GetMapping(value = "/indexdata")
    public Object indexdata(@RequestParam Long storeId) {
        //===========今日
        Map<String, String> timeArea = DateUtil.getTimeArea(0);
        String startTime = timeArea.get("startTime");
        String endTime = timeArea.get("endTime");
        ReportVo orderDataToday = getOrderDetail(startTime, endTime, storeId);//现金订单总额以及订单数对象
        ReportVo rechargeDataToday = getRechargeOrderDetail(startTime, endTime, storeId);//充值订单总额以及订单数对象
        ReportVo douyinDataToday = getHexiaoDetail(startTime, endTime, storeId, 0);
        ReportVo meituanDataToday = getHexiaoDetail(startTime, endTime, storeId, 1);
        ReportVo today = new ReportVo();
        today.setNum(orderDataToday.getNum()+rechargeDataToday.getNum()+douyinDataToday.getNum()+meituanDataToday.getNum());
        today.setMoney(orderDataToday.getMoney().add(rechargeDataToday.getMoney()).add(douyinDataToday.getMoney()).add(meituanDataToday.getMoney()));
        //=========昨日
        timeArea = DateUtil.getTimeArea(1);
        startTime = timeArea.get("startTime");
        endTime = timeArea.get("endTime");
        ReportVo orderDataYesterday = getOrderDetail(startTime, endTime, storeId);//现金订单总额以及订单数对象
        ReportVo rechargeDataYesterday = getRechargeOrderDetail(startTime, endTime, storeId);//充值订单总额以及订单数对象
        ReportVo douyinDataYesterday = getHexiaoDetail(startTime, endTime, storeId, 0);
        ReportVo meituanDataYesterday = getHexiaoDetail(startTime, endTime, storeId, 1);
        ReportVo yesterday = new ReportVo();
        yesterday.setNum(orderDataYesterday.getNum()+rechargeDataYesterday.getNum()+douyinDataYesterday.getNum()+meituanDataYesterday.getNum());
        yesterday.setMoney(orderDataYesterday.getMoney().add(rechargeDataYesterday.getMoney()).add(douyinDataYesterday.getMoney()).add(meituanDataYesterday.getMoney()));
        //==========本月
        timeArea = DateUtil.getTimeArea(2);
        startTime = timeArea.get("startTime");
        endTime = timeArea.get("endTime");
        ReportVo orderDataMonth = getOrderDetail(startTime, endTime, storeId);//现金订单总额以及订单数对象
        ReportVo rechargeDataMonth = getRechargeOrderDetail(startTime, endTime, storeId);//充值订单总额以及订单数对象
        ReportVo douyinDataMonth = getHexiaoDetail(startTime, endTime, storeId, 0);
        ReportVo meituanDataMonth = getHexiaoDetail(startTime, endTime, storeId, 1);
        ReportVo month = new ReportVo();
        month.setNum(orderDataMonth.getNum()+rechargeDataMonth.getNum()+douyinDataMonth.getNum()+meituanDataMonth.getNum());
        month.setMoney(orderDataMonth.getMoney().add(rechargeDataMonth.getMoney().add(douyinDataMonth.getMoney()).add(meituanDataMonth.getMoney())));
        Map<String, Object> result = new HashMap<>();
        result.put("today",today);
        result.put("yesterday",yesterday);
        result.put("month",month);
        return new CommonResult().success(result);
    }

    private List<ReportDetailVo> toReportDetail(List<DmsOrder> orders, List<QsgRechargeOrder> rechargeOrders, List<QsgHexiao> douyins, List<QsgHexiao> meituans) {
        List<ReportDetailVo> vos = new ArrayList<>();
        if (null != orders && orders.size() > 0) {
            for (DmsOrder order : orders) {
                ReportDetailVo vo = new ReportDetailVo();
                vo.setCreateDatetime(order.getCreateDatetime());
                QsgDevice device = deviceService.getById(order.getDeviceId());
                if (null != device) {
                    vo.setName(device.getMachineName());
                } else {
                    vo.setName("房间不存在");
                }
                vo.setOrderSn(order.getOrderSn());
                vo.setPrice(order.getPrice());
                vos.add(vo);
            }
        }
        if (null != rechargeOrders && rechargeOrders.size() > 0) {
            for (QsgRechargeOrder rechargeOrder : rechargeOrders) {
                ReportDetailVo vo = new ReportDetailVo();
                vo.setCreateDatetime(rechargeOrder.getCreateDatetime());
                vo.setName("用户充值");
                vo.setOrderSn(rechargeOrder.getOrderSn());
                vo.setPrice(rechargeOrder.getPrice());
                vos.add(vo);
            }
        }
        if (null != douyins && douyins.size() > 0) {
            for (QsgHexiao hexiao : douyins) {
                ReportDetailVo vo = new ReportDetailVo();
                vo.setCreateDatetime(hexiao.getCreateDatetime());
                vo.setName(hexiao.getMemberPhone());
                vo.setOrderSn(hexiao.getCode());
                vo.setPrice(hexiao.getPrice());
                vos.add(vo);
            }
        }
        if (null != meituans && meituans.size() > 0) {
            for (QsgHexiao hexiao : meituans) {
                ReportDetailVo vo = new ReportDetailVo();
                vo.setCreateDatetime(hexiao.getCreateDatetime());
                vo.setName(hexiao.getMemberPhone());
                vo.setOrderSn(hexiao.getCode());
                vo.setPrice(hexiao.getPrice());
                vos.add(vo);
            }
        }
        return vos;
    }

    private ReportVo getOrderDetail(String startTime, String endTime, Long storeId) {
        List<Integer> statusQw = new ArrayList<>();
        statusQw.add(OrderStatus.HAS_PAYMONEY.getValue());
        statusQw.add(OrderStatus.COMPLETED.getValue());
        QueryWrapper qw = new QueryWrapper();
        qw.eq("store_id", storeId);
        qw.in("order_status", statusQw);
        qw.eq("integral", 0);
        if (StringUtils.isNotBlank(startTime)) {
            qw.le("create_datetime", endTime);
            qw.ge("create_datetime", startTime);
        }
        int num = orderService.count(qw);
        qw.select("sum(price) as allMoney");
        DmsOrder order = orderService.getOne(qw);
        BigDecimal money = BigDecimal.ZERO;
        if (null != order && null != order.getAllMoney()) {
            money = order.getAllMoney();
        }
        ReportVo vo = new ReportVo();
        vo.setMoney(money);
        vo.setNum(num);
        return vo;
    }

    private ReportVo getHexiaoDetail(String startTime, String endTime, Long storeId, int type) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("store_id", storeId);
        qw.eq("hexiao_type", type);
        if (StringUtils.isNotBlank(startTime)) {
            qw.le("create_datetime", endTime);
            qw.ge("create_datetime", startTime);
        }
        int num = hexiaoService.count(qw);
        qw.select("sum(price) as allMoney");
        QsgHexiao hexiao = hexiaoService.getOne(qw);
        BigDecimal money = BigDecimal.ZERO;
        if (null != hexiao && null != hexiao.getAllMoney()) {
            money = hexiao.getAllMoney();
        }
        ReportVo vo = new ReportVo();
        vo.setMoney(money);
        vo.setNum(num);
        return vo;
    }

    private ReportVo getRechargeOrderDetail(String startTime, String endTime, Long storeId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("store_id", storeId);
        qw.eq("order_status", 2);
        if (StringUtils.isNotBlank(startTime)) {
            qw.le("create_datetime", endTime);
            qw.ge("create_datetime", startTime);
        }
        int num = rechargeOrderService.count(qw);
        qw.select("sum(price) as allMoney");
        QsgRechargeOrder order = rechargeOrderService.getOne(qw);
        BigDecimal money = BigDecimal.ZERO;
        if (null != order && null != order.getAllMoney()) {
            money = order.getAllMoney();
        }
        ReportVo vo = new ReportVo();
        vo.setMoney(money);
        vo.setNum(num);
        return vo;
    }

    /*
        今天
            订单状态为2/7的现金订单+订单状态为2的充值单
        昨天
        本月
        全部
     */
    @IgnoreAuth
    @GetMapping(value = "/getReport")
    public CommonResult getReport(Long storeId) {
        Map<String, Object> result = new HashMap<>();
        Map<String, String> timeArea = DateUtil.getTimeArea(0);
        String startTime = timeArea.get("startTime");
        String endTime = timeArea.get("endTime");
        ReportVo data = getOrderDetail(startTime, endTime, storeId);
        ReportVo rechargeData = getRechargeOrderDetail(startTime, endTime, storeId);
        result.put("todayMoney", data.getMoney().add(rechargeData.getMoney()));//今日金额
        result.put("todayOrderNum", data.getNum() + rechargeData.getNum());//今日
        //---------------昨日------------------------
        timeArea = DateUtil.getTimeArea(1);
        startTime = timeArea.get("startTime");
        endTime = timeArea.get("endTime");
        data = getOrderDetail(startTime, endTime, storeId);
        rechargeData = getRechargeOrderDetail(startTime, endTime, storeId);
        result.put("yesterdayMoney", data.getMoney().add(rechargeData.getMoney()));//昨日金额
        result.put("yesterdayNum", data.getNum() + rechargeData.getNum());//昨日
        //---------------------本月-------------------------------
        timeArea = DateUtil.getTimeArea(2);
        startTime = timeArea.get("startTime");
        endTime = timeArea.get("endTime");
        data = getOrderDetail(startTime, endTime, storeId);
        rechargeData = getRechargeOrderDetail(startTime, endTime, storeId);
        result.put("monthMoney", data.getMoney().add(rechargeData.getMoney()));//本月金额
        result.put("monthNum", data.getNum() + rechargeData.getNum());//本月
        return new CommonResult().success(result);
    }

    @IgnoreAuth
    @SysLog(MODULE = "dms", REMARK = "")
    @ApiOperation(value = "")
    @GetMapping(value = "/reportdetail")
    public Object coachOrderList(@RequestParam String status, @RequestParam Long storeId,
                                 @RequestParam(value = "pageSize", required = false, defaultValue = "30") Integer pageSize,
                                 @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum) {

        UmsMember member = UserUtils.getCurrentMember();
        Map<String, String> timeArea = DateUtil.getTimeArea(Integer.valueOf(status));
        String startTime = timeArea.get("startTime");
        String endTime = timeArea.get("endTime");
        ReportVo data = getOrderDetail(startTime, endTime, storeId);
        ReportVo rechargeData = getRechargeOrderDetail(startTime, endTime, storeId);
//        IPage<DmsOrder> page = null;
        QueryWrapper qw = new QueryWrapper();
        qw.eq("store_id", storeId);
        List<Integer> statusQw = new ArrayList<>();
        statusQw.add(OrderStatus.HAS_PAYMONEY.getValue());
        statusQw.add(OrderStatus.COMPLETED.getValue());
        qw.in("order_status", statusQw);
        qw.eq("integral", 0);
        qw.orderByDesc("create_datetime");
        if (StringUtils.isNotBlank(startTime)) {
            qw.le("create_datetime", endTime);
            qw.ge("create_datetime", startTime);
        }
        List<DmsOrder> orders = orderService.list(qw);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("store_id", storeId);
        queryWrapper.orderByDesc("create_datetime");
        queryWrapper.eq("order_status", 2);
        if (StringUtils.isNotBlank(startTime)) {
            queryWrapper.le("create_datetime", endTime);
            queryWrapper.ge("create_datetime", startTime);
        }
        List<QsgRechargeOrder> rechargeOrders = rechargeOrderService.list(queryWrapper);
        List<OrderVo> vos = new ArrayList<>();
        if (rechargeOrders.size() > 0) {
            for (QsgRechargeOrder order : rechargeOrders) {
                OrderVo vo = new OrderVo();
                vo.setName("用户充值");
                vo.setOrderSn(order.getOrderSn());
                vo.setCreateDatetime(DateUtil.dateToStr(order.getCreateDatetime(), "yyyy-MM-dd HH:mm:ss"));
                vo.setPrice(order.getPrice());
                vo.setNum(data.getNum() + rechargeData.getNum());
                vo.setMoney(data.getMoney().add(rechargeData.getMoney()));
                vos.add(vo);
            }
        }
        if (orders.size() > 0) {
            for (DmsOrder order : orders) {
                OrderVo vo = new OrderVo();
                QsgDevice device = deviceService.getById(order.getDeviceId());
                if (null != device) {
                    vo.setName(device.getMachineName());
                } else {
                    vo.setName("房间已删除");
                }
                vo.setOrderSn(order.getOrderSn());
                vo.setCreateDatetime(DateUtil.dateToStr(order.getCreateDatetime(), "yyyy-MM-dd HH:mm:ss"));
                vo.setPrice(order.getPrice());
                vo.setNum(data.getNum() + rechargeData.getNum());
                vo.setMoney(data.getMoney().add(rechargeData.getMoney()));
                vos.add(vo);
            }
        }
        return new CommonResult().success(vos);
    }
}
